package cn.daniellee.plugin.otp.listener;

import cn.daniellee.plugin.otp.menu.PlayerMenu;
import cn.daniellee.plugin.otp.menu.holder.PlayerMenuHolder;
import org.bukkit.Material;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.Listener;
import org.bukkit.event.inventory.CraftItemEvent;
import org.bukkit.event.inventory.InventoryClickEvent;
import org.bukkit.event.inventory.PrepareItemCraftEvent;
import org.bukkit.inventory.Inventory;
import org.bukkit.inventory.ItemStack;

public class MenuListener implements Listener {

	/**
	 * 处理排队菜单和确认菜单的点击事件
	 * @param e 事件
	 */
	@EventHandler
	public void onInventoryClick(InventoryClickEvent e) {
		Inventory menu = e.getInventory();
		if (menu != null && menu.getHolder() != null) {
			if (menu.getHolder() instanceof PlayerMenuHolder) {
				e.setCancelled(true);
				Player player = (Player) e.getWhoClicked();
				String itemName = e.getCurrentItem().getItemMeta().getDisplayName();
				if (e.getRawSlot() == 45 || e.getRawSlot() == 53) {
					Inventory playerMenu = PlayerMenu.generate(player.getName(), Integer.valueOf(itemName.substring(itemName.indexOf("[") + 1, itemName.indexOf("]"))));
					player.openInventory(playerMenu);
				} else {
					String targetName = itemName.substring(itemName.indexOf("a") + 1);
					if (e.getClick().isLeftClick()) {
						player.performCommand("otpa " + targetName);
						player.closeInventory();
					} else if (e.getClick().isRightClick()) {
						player.performCommand("otpahere " + targetName);
						player.closeInventory();
					}
				}
			}
		}
	}

}
